package com.alks.pad.service.last.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.aop.RedisLock;
import com.alks.common.service.RedisService;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.pad.commom.date.thread.PadUserIdThread;
import com.alks.pad.data.dto.last.PcLastStatusDto;
import com.alks.pad.data.dto.last.sizeNoDto;
import com.alks.pad.data.request.last.LastCollectDetailRequest;
import com.alks.pad.data.request.last.LotNoRequest;
import com.alks.pad.mapper.last.LastCollectDetailMapper;
import com.alks.pad.service.last.LastCollectDetailService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LastCollectDetailServiceImpl implements LastCollectDetailService {

    @Resource
    private LastCollectDetailMapper lastCollectDetailMapper;

    /**
     * 获取指令集合
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getLotNos(LotNoRequest request) {
        Map map = new HashMap();
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        List<String> list=lastCollectDetailMapper.getLotNos(request);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.error("查无数据,请核对指令!");
        }
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    /**
     * 获取指令详情
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo getLotDetail(String lotNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        Map<String, Object> lotDetail = lastCollectDetailMapper.getLotDetail(lotNo, companyId);
        return ResponseInfo.ok(lotDetail);
    }

    /**
     * 查询指令投产状况
     * @param request
     * @return
     */
    @Override
    public ResponseInfo LastCollectDetail(LotNoRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())) {
            return ResponseInfo.error("请先输入或者选择指令!");
        }
        String companyId = PadUserIdThread.get().getCompanyId();
        Map map = new HashMap();
        List<PcLastStatusDto> list = lastCollectDetailMapper.LastCollectDetail(request.getLotNo(), companyId);
        if (ObjectUtils.isEmpty(list)) {
            return ResponseInfo.warn("暂无数据,请核对指令!");
        }
        Integer ordQtyCount = 0;
        Integer prodQtyCount = 0;
        Integer unProdQtyCount = 0;
        Integer matchQtyCount = 0;
        for (PcLastStatusDto t : list) {
            if (t.getOrdQty() != null) {
                ordQtyCount += t.getOrdQty();
            }
            if (t.getProdQty() != null) {
                prodQtyCount += t.getProdQty();
            }
            if (t.getUnProdQty() != null) {
                unProdQtyCount += t.getUnProdQty();
            }
            if (t.getMatchQty() != null) {
                matchQtyCount += t.getMatchQty();
            }
        }
        map.put("list", list);
        map.put("ordQtyCount", ordQtyCount);
        map.put("prodQtyCount", prodQtyCount);
        map.put("unProdQtyCount", unProdQtyCount);
        map.put("matchQtyCount", matchQtyCount);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询当日投产记录
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo todayLastCollectDetail(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastCollectDetail> list = lastCollectDetailMapper.getTodayLastCollectDetail(companyId, deptNo);
        return ResponseInfo.ok(list);
    }

    /**
     * 查询当日投产状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo todayLastCollectDetailStatus(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<Map<String, Object>> list = lastCollectDetailMapper.getTodayLastCollectDetailStatus(companyId, deptNo);
        Map map = new HashMap();
        Integer count = 0;
        if (!ObjectUtils.isEmpty(list)){
            for (Map<String, Object> t : list) {
                count += Integer.parseInt(t.get("totalQty").toString());
            }
        }
        map.put("list", list);
        map.put("count",count);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询小时投产状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo hourLastCollectDetailStatus(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastCollectDetail> list = lastCollectDetailMapper.getTodayLastCollectDetail(companyId, deptNo);
        List<Map<String, Object>> objects = createHourSummary(list);
        return ResponseInfo.ok(objects);
    }

    /**
     * 创建小时汇总
     * @param list
     * @return
     */
    private List<Map<String, Object>> createHourSummary(List<PcLastCollectDetail> list) {
        List<Map<String, Object>> objects = new ArrayList<>();
        objects.add(createSummary(list, LocalTime.of(7, 30), LocalTime.of(8, 30), "7:30-8:30",1));
        objects.add(createSummary(list, LocalTime.of(8, 30), LocalTime.of(9, 30), "8:30-9:30",2));
        objects.add(createSummary(list, LocalTime.of(9, 30), LocalTime.of(10, 30), "9:30-10:30",3));
        objects.add(createSummary(list, LocalTime.of(10, 30), LocalTime.of(12, 0), "10:30-12:00",4));
        objects.add(createSummary(list, LocalTime.of(13, 0), LocalTime.of(14, 0), "13:00-14:00",5));
        objects.add(createSummary(list, LocalTime.of(14, 0), LocalTime.of(15, 0), "14:00-15:00",6));
        objects.add(createSummary(list, LocalTime.of(15, 0), LocalTime.of(16, 0), "15:00-16:00",7));
        objects.add(createSummary(list, LocalTime.of(16, 0), LocalTime.of(17, 0), "16:00-17:00",8));
        objects.add(createSummary(list, LocalTime.of(18, 0), LocalTime.of(19, 0), "18:00-19:00",9));
        objects.add(createSummary(list, LocalTime.of(19, 0), LocalTime.of(18, 0), "19:00-20:00",10));
        objects.add(createSummary(list, LocalTime.of(20, 0), LocalTime.of(21, 0), "20:00-21:00",11));
        objects.add(createSummary(list, LocalTime.of(21, 0), LocalTime.of(22, 0), "21:00-22:00",12));
        return objects;
    }

    /**
     * 对时间区间做汇总
     * @param list
     * @param startTime
     * @param endTime
     * @param label
     * @param seqNo
     * @return
     */
    private static Map<String, Object> createSummary(List<PcLastCollectDetail> list, LocalTime startTime, LocalTime endTime, String label,int seqNo) {
        int totalQty = list.stream()
                .filter(detail -> {
                    LocalDateTime collectTime = detail.getCollectTime();
                    LocalTime timeOfDay = collectTime.toLocalTime();
                    return !timeOfDay.isBefore(startTime) && !timeOfDay.isAfter(endTime);
                })
                .mapToInt(PcLastCollectDetail::getQty)
                .sum();
        Map<String, Object> map = new HashMap<>();
        map.put("seqNo", seqNo);
        map.put("date", label);
        map.put("count", totalQty);
        return map;
    }

    /**
     * 投产未满明细
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo unLastCollectDetail(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastStatusDto> list = lastCollectDetailMapper.unLastCollectDetail(deptNo, companyId);
        return ResponseInfo.ok(list);
    }

    @Autowired
    RedisService redisService;

    /**
     * 点击生产号码添加
     * @param request
     * @return
     */
    @Override
    @Transactional
    @RedisLock(key = "'key:add' + #request.lotNo +':' + #request.sizeNo ", expireTime = 1,message = "数据处理中,请稍后重试!")
    public ResponseInfo add(LastCollectDetailRequest request) {
        if (ZStringUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        String companyId = PadUserIdThread.get().getCompanyId();
        PcLotHead lotHead = lastCollectDetailMapper.getLotHead(request.getLotNo(), companyId);
        if (ZStringUtils.isNull(lotHead)){
            return ResponseInfo.error("指令信息不存在!");
        }
        if (!"Y".equals(lotHead.getCheckFlag())){
            return ResponseInfo.error("指令未审核!");
        }
        if (ZStringUtils.isEmpty(request.getLine())){
            return ResponseInfo.error("用户部门数据不能为空!");
        }
        if (ZStringUtils.isEmpty(request.getCollectUser())){
            return ResponseInfo.error("请选择相应的用户!");
        }
        if (ZStringUtils.isEmpty(request.getSizeNo())){
            return ResponseInfo.error("请选择号码!");
        }
        if (request.getQty()!=null &&request.getQty()>0){
            PcLotDetail detail = lastCollectDetailMapper.getLotDetailBySizeNo(companyId, request.getLotNo(), request.getSizeNo());
            Integer newOrdQty=detail.getOrderQty()!=null?detail.getOrderQty().intValue():0;
            //投产记录数量
            PcLastStatus pcLastStatus = lastCollectDetailMapper.getPcLastStatus(companyId, request.getLotNo(), request.getSizeNo());
            if (ObjectUtils.isEmpty(pcLastStatus)){
                if (newOrdQty< request.getQty()){
                    return ResponseInfo.error("采集数不能大于订单数!");
                }
                pcLastStatus = new PcLastStatus();
                pcLastStatus.setCompanyId(companyId);
                pcLastStatus.setLotNo(request.getLotNo());
                pcLastStatus.setSeqNo(detail.getSeqNo().intValue());
                pcLastStatus.setSizeNo(request.getSizeNo());
                pcLastStatus.setOrdQty(newOrdQty);
                pcLastStatus.setProdQty(request.getQty());
                lastCollectDetailMapper.addPcLastStatus(pcLastStatus);
            }else {
                Integer prodQty=pcLastStatus.getProdQty()!=null?pcLastStatus.getProdQty():0;
                if (newOrdQty==prodQty){
                    return ResponseInfo.error("该号码订单数已投完!");
                }
                if (newOrdQty< request.getQty()){
                    return ResponseInfo.error("采集数不能大于订单数!");
                }
                if (prodQty+request.getQty()>newOrdQty){
                    return ResponseInfo.error("投产数量不能大于订单数!");
                }
                //已产记录数量
                PcLastStatus2 pcLastStatus2 = lastCollectDetailMapper.getPcLastStatus2(companyId, request.getLotNo(), request.getSizeNo());
                if (!ObjectUtils.isEmpty(pcLastStatus2)){
                    Integer prodQty2=pcLastStatus2.getProdQty()!=null?pcLastStatus2.getProdQty():0;
                    if (prodQty2+request.getQty()>newOrdQty){
                        return ResponseInfo.error("号码订单数小于已产数量,请联系成控批次处理!");
                    }
                }
                Integer oldQty=pcLastStatus.getOrdQty()!=null?pcLastStatus.getOrdQty():0;
                if (newOrdQty>oldQty){
                    pcLastStatus.setOrdQty(newOrdQty);
                }else if (newOrdQty<oldQty){
                    if (request.getQty()+prodQty<newOrdQty){
                        pcLastStatus.setOrdQty(newOrdQty);
                        pcLastStatus.setProdQty(request.getQty()+prodQty);
                    }
                }else {
                    pcLastStatus.setProdQty(request.getQty()+prodQty);
                }
                lastCollectDetailMapper.updatePcLastStatus(pcLastStatus);
            }
            PcLastCollectDetail pcLastCollectDetail = new PcLastCollectDetail();
            BeanUtil.copyProperties(request, pcLastCollectDetail);
            pcLastCollectDetail.setCompanyId(companyId);
            pcLastCollectDetail.setCollectTime(LocalDateTime.now());
            lastCollectDetailMapper.addPcLastCollectDetail(pcLastCollectDetail);
        }else {
            return ResponseInfo.error("采集数必须大于0!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 号码明细
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo SizeByLotNo(String companyId, String lotNo) {
        List<sizeNoDto> list = lastCollectDetailMapper.SizeByLotNo(lotNo, companyId);
        return ResponseInfo.ok(list);
    }

    /**
     * 当日投产记录删除
     * @param request
     * @return
     */
    @Override
    @Transactional
    @RedisLock(key = "'key:delLastCollectDetail' + #request.lotNo + ':' + #request.sizeNo ", expireTime = 1,message = "数据处理中,请稍后重试!")
    public ResponseInfo delLastCollectDetail(LastCollectDetailRequest request) {
        if (ZStringUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        if (ZStringUtils.isEmpty(request.getLine())){
            return ResponseInfo.error("用户部门数据不能为空!");
        }
        if (ZStringUtils.isEmpty(request.getSizeNo())){
            return ResponseInfo.error("号码不能为空!");
        }
        if (request.getQty()==null){
            return ResponseInfo.error("采集数不能为空!");
        }
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        PcLastStatus pcLastStatus = lastCollectDetailMapper.getPcLastStatus(companyId, request.getLotNo(), request.getSizeNo());
        PcLastStatus2 pcLastStatus2 = lastCollectDetailMapper.getPcLastStatus2(companyId, request.getLotNo(), request.getSizeNo());
        Integer qty = request.getQty();
        Integer prodQty=pcLastStatus.getProdQty()!=null?pcLastStatus.getProdQty():0;
        if(!ObjectUtils.isEmpty(pcLastStatus2)){
            Integer prodQty2=pcLastStatus2.getProdQty()!=null?pcLastStatus2.getProdQty():0;
            if (prodQty-qty<prodQty2){
                return ResponseInfo.error("投产数量不能少于产出数量,不能删除!");
            }
            pcLastStatus.setProdQty(prodQty-qty);
            lastCollectDetailMapper.updatePcLastStatus(pcLastStatus);
            lastCollectDetailMapper.delLastCollectDetail(request);
        }else {
            pcLastStatus.setProdQty(prodQty-qty);
            lastCollectDetailMapper.updatePcLastStatus(pcLastStatus);
            lastCollectDetailMapper.delLastCollectDetail(request);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 产出号码添加
     * @param request
     * @return
     */
    @Override
    @Transactional
    @RedisLock(key = "'key:produceAdd' + #request.lotNo + ':' + #request.sizeNo ", expireTime = 1,message = "数据处理中,请稍后重试!")
    public ResponseInfo produceAdd(LastCollectDetailRequest request) {
        if (ZStringUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        String companyId = PadUserIdThread.get().getCompanyId();
        PcLotHead lotHead = lastCollectDetailMapper.getLotHead(request.getLotNo(), companyId);
        if (ZStringUtils.isNull(lotHead)){
            return ResponseInfo.error("指令信息不存在!");
        }
        if (!"Y".equals(lotHead.getCheckFlag())){
            return ResponseInfo.error("指令未审核!");
        }
        if (ZStringUtils.isEmpty(request.getLine())){
            return ResponseInfo.error("用户部门数据不能为空!");
        }
        if (ZStringUtils.isEmpty(request.getCollectUser())){
            return ResponseInfo.error("请选择相应的用户!");
        }
        if (ZStringUtils.isEmpty(request.getSizeNo())){
            return ResponseInfo.error("请选择号码!");
        }

        if (request.getQty()!=null &&request.getQty()>0){
            PcLotDetail detail = lastCollectDetailMapper.getLotDetailBySizeNo(companyId, request.getLotNo(), request.getSizeNo());
            Integer newOrdQty=detail.getOrderQty()!=null?detail.getOrderQty().intValue():0;
            if (newOrdQty<request.getQty()){
                return ResponseInfo.error("采集数不能大于订单数!");
            }
            PcLastStatus pcLastStatus = lastCollectDetailMapper.getPcLastStatus(companyId, request.getLotNo(), request.getSizeNo());
            if (ObjectUtils.isEmpty(pcLastStatus)){
                return ResponseInfo.error("该指令号码未投产!");
            }
            Integer prodQty=pcLastStatus.getProdQty()!=null?pcLastStatus.getProdQty():0;
            PcLastStatus2 pcLastStatus2 = lastCollectDetailMapper.getPcLastStatus2(companyId, request.getLotNo(), request.getSizeNo());
            if (!ObjectUtils.isEmpty(pcLastStatus2)){
                Integer prodQty2=pcLastStatus2.getProdQty()!=null?pcLastStatus2.getProdQty():0;
                if (prodQty2+request.getQty()>prodQty){
                    return ResponseInfo.error("采集数量不能大于投产数量!");
                }
                if (request.getQty()+prodQty2>newOrdQty){
                    return ResponseInfo.error("采集数量大于订单数,请联系成控批次处理!");
                }
                pcLastStatus2.setOrdQty(newOrdQty);
                pcLastStatus2.setProdQty(prodQty2+request.getQty());
                lastCollectDetailMapper.updatePcLastStatus2(pcLastStatus2);
            }else {
                if (prodQty<request.getQty()){
                    return ResponseInfo.error("采集数量不能大于投产数量!");
                }
                pcLastStatus2 = new PcLastStatus2();
                pcLastStatus2.setCompanyId(companyId);
                pcLastStatus2.setLotNo(request.getLotNo());
                pcLastStatus2.setSeqNo(detail.getSeqNo().intValue());
                pcLastStatus2.setSizeNo(request.getSizeNo());
                pcLastStatus2.setOrdQty(newOrdQty);
                pcLastStatus2.setProdQty(request.getQty());
                lastCollectDetailMapper.addPcLastStatus2(pcLastStatus2);
            }
            PcLastCollectDetail pcLastCollectDetail = new PcLastCollectDetail();
            BeanUtil.copyProperties(request, pcLastCollectDetail);
            pcLastCollectDetail.setCompanyId(companyId);
            pcLastCollectDetail.setCollectTime(LocalDateTime.now());
            lastCollectDetailMapper.addPcLastCollectDetail2(pcLastCollectDetail);
        }else {
            return ResponseInfo.error("采集数必须大于0!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 前段查询指令
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getFrontSectionLotNo(LastCollectDetailRequest request) {
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        List<String> lotNos = lastCollectDetailMapper.getFrontSectionLotNo(request);
        return ResponseInfo.ok(lotNos);
    }

    /**
     * 查询指令产出状况
     * @param request
     * @return
     */
    @Override
    public ResponseInfo LastCollectDetail2(LotNoRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("请输入指令!");
        }
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        List<PcLastStatusDto> list = lastCollectDetailMapper.LastCollectDetail2(request);
        if (ObjectUtils.isEmpty(list)) {
            return ResponseInfo.warn("暂无数据,请核对指令!");
        }
        Map<String, Object> map = new HashMap<>();
        Integer ordQtyCount = 0;
        Integer prodQtyCount = 0;
        Integer unProdQtyCount = 0;
        Integer produceQty = 0;
        Integer unProduceQty = 0;
        for (PcLastStatusDto t : list) {
            if (t.getOrdQty() != null) {
                ordQtyCount += t.getOrdQty();
            }
            if (t.getProdQty() != null) {
                prodQtyCount += t.getProdQty();
            }
            if (t.getUnProdQty() != null) {
                unProdQtyCount += t.getUnProdQty();
            }
            if (t.getProduceQty() != null) {
                produceQty += t.getProduceQty();
            }
            if (t.getUnProduceQty()!=null){
                unProduceQty+= t.getUnProduceQty();
            }
        }
        map.put("list", list);
        map.put("ordQtyCount", ordQtyCount);
        map.put("prodQtyCount", prodQtyCount);
        map.put("unProdQtyCount", unProdQtyCount);
        map.put("produceQty", produceQty);
        map.put("unProduceQty", unProduceQty);
        return ResponseInfo.ok(map);
    }

    /**
     * 小时产出状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo hourLastCollectDetail2Status(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastCollectDetail> list = lastCollectDetailMapper.getTodayLastCollectDetail2(companyId, deptNo);
        List<Map<String, Object>> objects = createHourSummary(list);
        return ResponseInfo.ok(objects);
    }

    /**
     * 小时产出状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo todayLastCollectDetail2(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastCollectDetail> list = lastCollectDetailMapper.getTodayLastCollectDetail2(companyId, deptNo);
        return ResponseInfo.ok(list);
    }

    /**
     * 当日产出状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo todayLastCollectDetail2Status(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<Map<String, Object>> list = lastCollectDetailMapper.getTodayLastCollectDetail2Status(companyId, deptNo);
        Map map = new HashMap();
        Integer count = 0;
        if (!ObjectUtils.isEmpty(list)){
            for (Map<String, Object> t : list) {
                count += Integer.parseInt(t.get("totalQty").toString());
            }
        }
        map.put("list", list);
        map.put("count",count);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    @RedisLock(key = "'key:delLastCollectDetail2' + #request.lotNo + ':' + #request.sizeNo ", expireTime = 1,message = "数据处理中,请稍后重试!")
    public ResponseInfo delLastCollectDetail2(LastCollectDetailRequest request) {
        if (ZStringUtils.isEmpty(request.getLotNo())) {
            return ResponseInfo.error("指令不能为空!");
        }
        if (ZStringUtils.isEmpty(request.getLine())) {
            return ResponseInfo.error("用户部门数据不能为空!");
        }
        if (ZStringUtils.isEmpty(request.getSizeNo())) {
            return ResponseInfo.error("号码不能为空!");
        }
        if (request.getQty() == null) {
            return ResponseInfo.error("采集数不能为空!");
        }
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        PcLastStatus2 pcLastStatus2 = lastCollectDetailMapper.getPcLastStatus2(companyId, request.getLotNo(), request.getSizeNo());
        if (ObjectUtils.isEmpty(pcLastStatus2)){
            return ResponseInfo.error("产出明细不存在!");
        }
        Integer qty = request.getQty();
        Integer prodQty = pcLastStatus2.getProdQty() != null ? pcLastStatus2.getProdQty() : 0;
        pcLastStatus2.setProdQty(prodQty - qty);
        lastCollectDetailMapper.updatePcLastStatus2(pcLastStatus2);
        lastCollectDetailMapper.delLastCollectDetail2(request);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 不良原因
     * @param deptType
     * @return
     */
    @Override
    public ResponseInfo reasons(String deptType) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcQualityType> reasonList = lastCollectDetailMapper.getReasonList(deptType, companyId);
        return ResponseInfo.ok(reasonList);
    }

    /**
     * 当日录入记录
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo dayAddList(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastingQualityCollect> list = lastCollectDetailMapper.getDayAdd(companyId, deptNo);
        return ResponseInfo.ok(list);
    }

    /**
     * 当日品质状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo dayQualityStatus(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastingQualityCollect> list = lastCollectDetailMapper.getDayAdd(companyId, deptNo);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.ok();
        }
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Integer> data = list.stream()
                .collect(Collectors.groupingBy(PcLastingQualityCollect::getQualityName,
                        Collectors.summingInt(PcLastingQualityCollect::getQty)));

        Integer passCount = list.stream()
                .filter(item -> "合格".equals(item.getQualityName()))
                .mapToInt(PcLastingQualityCollect::getQty)
                .sum();

        Integer noPassCount = list.stream()
                .filter(item -> !"合格".equals(item.getQualityName()))
                .mapToInt(PcLastingQualityCollect::getQty)
                .sum();
        map.put("data", data);
        map.put("noPassCount", noPassCount);
        if (passCount ==null || passCount == 0) {
            map.put("defectRate", "0.0");
        }else {
            noPassCount = noPassCount == null ? 0 : noPassCount;
            Integer count=noPassCount+passCount;
            double defectRate =(noPassCount /(double)count) * 100;
            map.put("defectRate", String.format("%.1f", defectRate));
        }
        return ResponseInfo.ok(map);
    }

    /**
     * 小时品质状况
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo hourQualityStatus(String deptNo) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<PcLastingQualityCollect> list = lastCollectDetailMapper.getDayAdd(companyId, deptNo);
        List<Map<String, Object>> objects = createHourQualityStatusSummary(list);
        return ResponseInfo.ok(objects);
    }

    /**
     * 创建小时汇总
     * @param list
     * @return
     */
    private List<Map<String, Object>> createHourQualityStatusSummary(List<PcLastingQualityCollect> list) {
        List<Map<String, Object>> objects = new ArrayList<>();
        objects.add(createSummary2(list, LocalTime.of(7, 30), LocalTime.of(8, 30), "7:30-8:30",1));
        objects.add(createSummary2(list, LocalTime.of(8, 30), LocalTime.of(9, 30), "8:30-9:30",2));
        objects.add(createSummary2(list, LocalTime.of(9, 30), LocalTime.of(10, 30), "9:30-10:30",3));
        objects.add(createSummary2(list, LocalTime.of(10, 30), LocalTime.of(12, 0), "10:30-12:00",4));
        objects.add(createSummary2(list, LocalTime.of(13, 0), LocalTime.of(14, 0), "13:00-14:00",5));
        objects.add(createSummary2(list, LocalTime.of(14, 0), LocalTime.of(15, 0), "14:00-15:00",6));
        objects.add(createSummary2(list, LocalTime.of(15, 0), LocalTime.of(16, 0), "15:00-16:00",7));
        objects.add(createSummary2(list, LocalTime.of(16, 0), LocalTime.of(17, 0), "16:00-17:00",8));
        objects.add(createSummary2(list, LocalTime.of(18, 0), LocalTime.of(19, 0), "18:00-19:00",9));
        objects.add(createSummary2(list, LocalTime.of(19, 0), LocalTime.of(18, 0), "19:00-20:00",10));
        objects.add(createSummary2(list, LocalTime.of(20, 0), LocalTime.of(21, 0), "20:00-21:00",11));
        objects.add(createSummary2(list, LocalTime.of(21, 0), LocalTime.of(22, 0), "21:00-22:00",12));
        return objects;
    }

    /**
     * 对时间区间做汇总
     * @param list
     * @param startTime
     * @param endTime
     * @param label
     * @param seqNo
     * @return
     */
    private Map<String, Object> createSummary2(List<PcLastingQualityCollect> list, LocalTime startTime, LocalTime endTime, String label, int seqNo) {
        int count = list.stream()
                .filter(detail -> {
                    LocalDateTime collectTime = detail.getCollectTime();
                    LocalTime timeOfDay = collectTime.toLocalTime();
                    return !timeOfDay.isBefore(startTime) && !timeOfDay.isAfter(endTime);
                })
                .mapToInt(PcLastingQualityCollect::getQty)
                .sum();

        //不合格数量
        int noPassCount = list.stream()
                .filter(detail -> {
                    LocalDateTime collectTime = detail.getCollectTime();
                    LocalTime timeOfDay = collectTime.toLocalTime();
                    return !timeOfDay.isBefore(startTime) && !timeOfDay.isAfter(endTime)
                            && !"合格".equals(detail.getQualityName());
                })
                .mapToInt(PcLastingQualityCollect::getQty)
                .sum();

        double defectRate = count == 0 ? 0 : (noPassCount /(double) count) * 100;
        Map<String, Object> map = new HashMap<>();
        map.put("seqNo", seqNo);
        map.put("date", label);
        map.put("defectRate", String.format("%.1f", defectRate));
        return map;
    }

    /**
     * 当日录入记录-删除
     * @param request
     * @return
     */
    @Override
    public ResponseInfo delPcLastingQualityCollect(PcLastingQualityCollect request) {
        if (ObjectUtils.isEmpty(request.getDeptNo())){
            return ResponseInfo.error("用户部门数据不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getCollectTime())){
            return ResponseInfo.error("收集时间不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getQty())){
            return ResponseInfo.error("采集数量不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getQualityType())|| ObjectUtils.isEmpty(request.getQualityName())){
            return ResponseInfo.error("不良原因不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getCompanyId())){
            return ResponseInfo.error("公司编号不能为空!");
        }
        lastCollectDetailMapper.delPcLastingQualityCollect(request);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 添加
     * @param request
     * @return
     */
    @Override
    public ResponseInfo addPcLastingQualityCollect(PcLastingQualityCollect request) {
        if (ObjectUtils.isEmpty(request.getDeptNo())){
            return ResponseInfo.error("用户部门数据不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getQty())){
            return ResponseInfo.error("采集数量不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getCollectUser())){
            return ResponseInfo.error("采集人不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getQualityType())|| ObjectUtils.isEmpty(request.getQualityName())){
            return ResponseInfo.error("不良原因不能为空!");
        }
        request.setCollectTime(LocalDateTime.now());
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        lastCollectDetailMapper.addPcLastingQualityCollect(request);
        return ResponseInfo.ok("操作成功!");
    }
}
